package com.jvup.common.utils;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.asynclayoutinflater.view.AsyncLayoutInflater;
import androidx.asynclayoutinflater.view.AsyncLayoutInflater.OnInflateFinishedListener;
import androidx.lifecycle.Lifecycle;

import com.jvup.common.SummerApp;
import com.jvup.common.GlideApp;
import com.jvup.common.R;
import com.jvup.common.basic.StringUtil;
import com.jvup.common.support.base.BaseActivity;
import com.jvup.common.widget.snackbar.Prompt;
import com.jvup.common.widget.snackbar.SnackBar;
import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

public class ToastHelper {

    private final static Handler handler = new Handler(Looper.getMainLooper());

    private static Toast toast;
    private static Toast customToast;

    public static void showToast(final String text) {
        if(Looper.getMainLooper() == Looper.myLooper()) {
            toast = Toast.makeText(SummerApp.summerApp(), text, Toast.LENGTH_SHORT);
            toast.show();
        } else {
            // 子线程Toast
            handler.post(() -> showToast(text));
        }
    }

    public static void showToastWithoutDelay(final String text) {
        if(toast != null) {
            toast.cancel();
        }
        if(Looper.getMainLooper() == Looper.myLooper()) {
            toast = Toast.makeText(SummerApp.summerApp(), text, Toast.LENGTH_SHORT);
            toast.show();
        } else {
            // 子线程Toast
            handler.post(() -> showToastWithoutDelay(text));
        }
    }

    public static void showSnackBar(String text, Prompt promptType) {
        BaseActivity baseActivity = (BaseActivity) ActivityManageHandler.HANDLER.currentActivity();
        if(baseActivity != null) {
            boolean needStatusBarHeight = false;
            if(baseActivity.isFullScreen())
                needStatusBarHeight = true;
            showSnackBar(baseActivity,text, promptType,needStatusBarHeight);
        } else {
            showToast(text);
        }
    }

    public static void showSnackBarAtPreviousPage(String text, Prompt promptType) {
        BaseActivity baseActivity = (BaseActivity) ActivityManageHandler.HANDLER.previousActivity();
        if(baseActivity != null) {
            boolean needStatusBarHeight = false;
            if(baseActivity.isFullScreen())
                needStatusBarHeight = true;
            showSnackBar(baseActivity,text, promptType,needStatusBarHeight);
        } else {
            showToast(text);
        }
    }

    private static void showSnackBar(BaseActivity activity, CharSequence msgText, final Prompt promptType, boolean needStatusBarHeight) {
        final int statusBarHeight = needStatusBarHeight ? EquipmentInfoUtil.statusBarHeight() : 0;
        SnackBar snackBar = SnackBar.make(activity.getWindow().getDecorView(), msgText, SnackBar.LENGTH_LONG, promptType.layoutRid)
                .setGravity(Gravity.TOP)
                .updateViewAttribute(R.id.snackbar_root,view -> ((FrameLayout.LayoutParams)view.getLayoutParams()).topMargin = statusBarHeight)
                .<ImageView>updateViewAttribute(R.id.snackbar_icon,view -> view.setImageResource(promptType.resIcon));

        new ScheduledTaskHelper(activity.getLifecycle())
                .buildTask(snackBar)
                .setConditional(Lifecycle.State.RESUMED)
                .setTask(bar -> {
                    bar.show();
                    return true;
                }).submitAndDoTask();
    }

    /**
     * 黑色透明
     * @param lightText
     * @param darkText
     */
    public static void showCenterDarkToast(CharSequence lightText, CharSequence darkText) {
        showDarkToast(lightText,darkText, Gravity.CENTER);
    }
    public static void showDarkToast(CharSequence lightText, CharSequence darkText, int gravity) {
        HashMap<Integer, Object> viewModel = new HashMap<>();
        viewModel.put(R.id.common_toast_light_text,lightText);
        viewModel.put(R.id.common_toast_dark_text,darkText);
        showCustomToast(R.layout.common_toast_dark_center,gravity,viewModel);
    }

    public static void showCustomToast(int layoutRid) {
        showCustomToast(layoutRid, Gravity.CENTER);
    }
    public static void showCustomToast(int layoutRid,int gravity) {
        showCustomToast(layoutRid,gravity,null);
    }
    public static void showCustomToast(int layoutRid, int gravity, HashMap viewModel) {
        showCustomToast(layoutRid,gravity,viewModel,null);
    }
    public static void showCustomToast(int layoutRid, int gravity, HashMap viewModel, HashMap controller) {
        new Thread(() -> {
            handler.post(() -> asyncInflaterLayout(layoutRid,gravity,viewModel,controller));
        }).start();
    }

    private static void asyncInflaterLayout(int layoutRid, int gravity, HashMap viewModel, HashMap controller) {
        AsyncLayoutInflater inflater = new AsyncLayoutInflater(SummerApp.summerApp());
        inflater.inflate(layoutRid,null,new InflateFinishedListener(gravity,viewModel,controller));
    }
    private static class InflateFinishedListener implements OnInflateFinishedListener {

        private final int gravity;
        private final HashMap<Integer, Object> viewModel;
        private final HashMap<Integer, View.OnClickListener> controller;

//        private final Object viewModel;
//        private final Object controller;
//        public InflateFinishedListener(int gravity,Object viewModel,Object controller){}

        public InflateFinishedListener(int gravity, HashMap viewModel, HashMap controller){
            this.gravity    = gravity;
            this.viewModel  = viewModel;
            this.controller = controller;
        }

        public void onInflateFinished(@NonNull View layout, @LayoutRes int layoutRid, @Nullable ViewGroup parent) {
            if(customToast != null){
                customToast.cancel();
            }

            customToast = new Toast(SummerApp.summerApp());
            customToast.setView(layout);
            customToast.setGravity(gravity, 0, 0);
            customToast.show();

//            ViewDataBinding viewDataBinding = DataBindingUtil.bind(layout);
//            viewDataBinding.setVariable(BR.viewModel,viewModel);
//            viewDataBinding.setVariable(BR.controller,controller);

            if(viewModel != null)
                fillData(layout,viewModel);
            if(controller != null) {
                bindListener(layout, controller);
                //反射获取layoutParams
                WindowManager.LayoutParams layoutParams = getWindowParams(customToast);
                //清空flags置位
                if(layoutParams!=null)
                    layoutParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            }

        }

        private WindowManager.LayoutParams getWindowParams(Toast toast){
            WindowManager.LayoutParams layoutParams = null;
            try {
                Method method = Toast.class.getDeclaredMethod("getWindowParams");
                if(method!=null)
                    layoutParams = (WindowManager.LayoutParams) method.invoke(toast);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            return layoutParams;
        }

        private void fillData(View layout, HashMap<Integer,?> viewModel) {
            for(Integer key : viewModel.keySet()) {
                View view = layout.findViewById(key);
                if(view instanceof TextView){
                    TextView textView = (TextView) view;
                    Object text = viewModel.get(key);
                    if(text==null|| StringUtil.isEmpty(text.toString()))
                        textView.setVisibility(View.GONE);
                    else
                        textView.setVisibility(View.VISIBLE);
                    textView.setText(String.valueOf(text));
                    continue;
                }
                if(view instanceof ImageView){
                    ImageView imageView = (ImageView) view;
                    Object image = viewModel.get(key);
                    if(image instanceof Integer) {
                        imageView.setImageResource((int) image);
                        continue;
                    }
                    if(image instanceof String){
                        GlideApp.with(view.getContext())
                                .load(image)
                                .into(imageView);
                        continue;
                    }
                    if(image instanceof Bitmap){
                        imageView.setImageBitmap((Bitmap) image);
                        continue;
                    }
                }
            }
        }

        private void bindListener(View layout, HashMap<Integer, View.OnClickListener> controller){
            for(Integer key : controller.keySet()) {
                View view = layout.findViewById(key);
                view.setOnClickListener(controller.get(key));
            }
        }

    }

}
